package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.ConsolidatedOrdersMapper;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.YY1_KPI;
import com.topcent.tioxyc.pojo.vo.ConsolidatedOrderVO;
import com.topcent.tioxyc.pojo.vo.Lin;
import com.topcent.tioxyc.pojo.vo.ToChangeVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/2/13 14:01
 * @Description: 销售订单统计
 */
@Slf4j
@Component
public class ConsolidatedOrdersXxlJob {
    @Autowired
    private ConsolidatedOrdersMapper consolidatedOrdersMapper;

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @XxlJob("ConsolidatedOrders")
    public void execute() {
        consolidatedOrdersMapper.truncateTable();
        List<ConsolidatedOrders> chaxun = consolidatedOrdersMapper.chaxun();
        List<ConsolidatedOrders> bian = consolidatedOrdersMapper.bian();
        List<ConsolidatedOrders> bian25_26 = consolidatedOrdersMapper.bian25_26();
        chaxun.addAll(bian);
        chaxun.addAll(bian25_26);
        Header[] headers = ConnmeUtils.createHeaders();
        for (ConsolidatedOrders consolidatedOrders : chaxun) {
            BigDecimal fy2324dde = consolidatedOrders.getFy23_24dde();

            if (fy2324dde!=null){
                if (fy2324dde.compareTo(new BigDecimal("10000000")) >= 0) {
                    consolidatedOrders.setKhdji23("GSKA");
                } else if (fy2324dde.compareTo(new BigDecimal("3000000")) >= 0) {
                    consolidatedOrders.setKhdji23("SKA");
                } else if (fy2324dde.compareTo(new BigDecimal("1000000")) >= 0) {
                    consolidatedOrders.setKhdji23("KA");
                } else if (fy2324dde.compareTo(new BigDecimal("300000")) >= 0) {
                    consolidatedOrders.setKhdji23("PA");
                } else {
                    consolidatedOrders.setKhdji23("AA");
                }
            }
            BigDecimal fy2425dde = consolidatedOrders.getFy24_25dde();
            if (fy2425dde!=null){
                if (fy2425dde.compareTo(new BigDecimal("10000000")) >= 0) {
                    consolidatedOrders.setKhdji24("GSKA");
                } else if (fy2425dde.compareTo(new BigDecimal("3000000")) >= 0) {
                    consolidatedOrders.setKhdji24("SKA");
                } else if (fy2425dde.compareTo(new BigDecimal("1000000")) >= 0) {
                    consolidatedOrders.setKhdji24("KA");
                } else if (fy2425dde.compareTo(new BigDecimal("300000")) >= 0) {
                    consolidatedOrders.setKhdji24("PA");
                } else if(fy2425dde.compareTo(new BigDecimal("0")) > 0){
                    consolidatedOrders.setKhdji24("AA");
                }
            }
            BigDecimal fy2526dde = consolidatedOrders.getFy25_26dde();
            if (fy2526dde!=null){
                if (fy2526dde.compareTo(new BigDecimal("10000000")) >= 0) {
                    consolidatedOrders.setKhdji25("GSKA");
                } else if (fy2526dde.compareTo(new BigDecimal("3000000")) >= 0) {
                    consolidatedOrders.setKhdji25("SKA");
                } else if (fy2526dde.compareTo(new BigDecimal("1000000")) >= 0) {
                    consolidatedOrders.setKhdji25("KA");
                } else if (fy2526dde.compareTo(new BigDecimal("300000")) >= 0) {
                    consolidatedOrders.setKhdji25("PA");
                } else if(fy2526dde.compareTo(new BigDecimal("0")) > 0){
                    consolidatedOrders.setKhdji25("AA");
                }
            }
            Map<String, Object> shenqing = new HashMap<>();
            shenqing.put("app_id", "66a6f42ff97af74b02d217df");
            // 客户主数据
            shenqing.put("entry_id", "66a6f443333584e2c128154f");

            if (consolidatedOrders.getJdrq() == null &&consolidatedOrders.getId()==null) {
                HashMap<String, String > shenqingdan1=new HashMap<>();
                shenqingdan1.put("_widget_1722305048887",consolidatedOrders.getSapid());
                List<Customer> customersSum = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan1, Customer.class);
                if (CollectionUtils.isNotEmpty(customersSum)) {
                    Date widget1733204191654 = customersSum.getFirst().get_widget_1733204191654();
                    consolidatedOrders.setJdrq(widget1733204191654);
                    String widget1722217596682 = customersSum.getFirst().get_widget_1722217596682();
                    consolidatedOrders.setKhmc(widget1722217596682);
                }
            }
            if (StringUtils.isBlank(consolidatedOrders.getSapid())){
                HashMap<String, String > shenqingdan2=new HashMap<>();
                shenqingdan2.put("_widget_1728356780097",consolidatedOrders.getId());
                List<Customer> customers = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan2, Customer.class);
                if (CollectionUtils.isNotEmpty(customers)){
                    String widget1722305048887= customers.getFirst().get_widget_1722305048887();
                    consolidatedOrders.setSapid(widget1722305048887);
                    String widget1722217596682 = customers.getFirst().get_widget_1722217596682();
                    consolidatedOrders.setKhmc(widget1722217596682);
                }
            }

            HashMap<String, String > shenqingdan2=new HashMap<>();
            shenqingdan2.put("_widget_1722305048887",consolidatedOrders.getSapid());
            List<CustomerVO> customersSum2 = PurchaseCommunity.queryBased(shenqing, headers, shenqingdan2, CustomerVO.class);
                if (CollectionUtils.isNotEmpty(customersSum2)) {
                    // 解析为 JSONObject
                    JSONObject json = JSONUtil.parseObj(customersSum2.getFirst().get_widget_1722217596692());
                    consolidatedOrders.setBmmc(json.getStr("name"));
                    consolidatedOrders.setBmmcId(Integer.parseInt(json.getStr("dept_no")));
                    consolidatedOrders.setYwy(customersSum2.getFirst() != null && customersSum2.getFirst().get_widget_1722302059749() != null
                            ? customersSum2.getFirst().get_widget_1722302059749().getName()
                            : "");
                }

            //过滤数据
            consolidatedOrders.setYwy(extractName(consolidatedOrders.getYwy()));
            // 插入数据库表ConsolidatedOrders
            consolidatedOrdersMapper.insert(consolidatedOrders);
        }
        // 查询到表单老客户跟踪：67c948db070e1676545913c8
        selectAndList(headers);
    }

    public void selectAndList(Header[] headers){
        // 获取到表单老客户跟踪表单数据。
        List<Lin> consolidatedOrderVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6625db7ad51ac01aab98a910");
        parameter.put("entry_id", "67c948db070e1676545913c8");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Lin> list = JSONUtil.toList(objects, Lin.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            consolidatedOrderVOList.addAll(list);
        } while (fale);
        // 判断集合是否有值 有则删除 一次只能删除100条
        if (CollectionUtils.isNotEmpty(consolidatedOrderVOList)) {
            // 提取所有数据ID
            List<String> dataIds = consolidatedOrderVOList.stream()
                    .map(Lin::get_id) // get_id() 是获取数据ID的方法
                    .collect(Collectors.toList());

            int batchSize = 100;
            for (int i = 0; i < dataIds.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, dataIds.size());
                List<String> batchDataIds = dataIds.subList(i, endIndex);

                // 构造删除接口请求参数
                Map<String, Object> deleteParam = new HashMap<>();
                deleteParam.put("app_id", "6625db7ad51ac01aab98a910");
                deleteParam.put("entry_id", "67c948db070e1676545913c8");
                deleteParam.put("data_ids", batchDataIds);

                // 发送删除请求
                String jsonDelete = JSONUtil.toJsonStr(deleteParam);
                JSONObject deleteResponse = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_delete", headers, jsonDelete);
                // 记录响应日志,判断删除是否成功
                log.info("删除接口响应：{}", deleteResponse);
            }
        }
        //查询ConsolidatedOrders表数据。通过ywy 对应 客户主数据表单的name拿到username。
        List<ConsolidatedOrders> selectAndList = consolidatedOrdersMapper.selectAndList();
        // 获取客户主数据表单数据。
        //ccName集合
        List<CustomerVO.ccName> ccNameList = new ArrayList<>();
        Map<String, Object> shenqing = new HashMap<>();
        shenqing.put("app_id", "66a6f42ff97af74b02d217df");
        // 客户主数据
        shenqing.put("entry_id", "66a6f443333584e2c128154f");
        boolean fales = true;
        String zhs = "";
        do {
            if (!zhs.isEmpty()) {
                shenqing.put("data_id", zhs);
            }
            shenqing.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(shenqing);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<CustomerVO> list = JSONUtil.toList(objects, CustomerVO.class);
            if (list.size() == 100) {
                zhs = list.getLast().get_id();
            } else {
                fales = false;
            }

            for (CustomerVO customer : list) {
                if (ObjectUtils.isEmpty(customer.get_widget_1722302059749())) {
                   continue;
                }
                ccNameList.add(customer.get_widget_1722302059749());
            }
        } while (fales);

        log.info("老客户跟踪表单数据size：{}", consolidatedOrderVOList.size());
        // 构建映射表
        Map<String, String> nameToUsernameMap = new HashMap<>();
        for (CustomerVO.ccName ccName : ccNameList) {
            if(ObjectUtils.isNotEmpty(ccName)){
                nameToUsernameMap.put(ccName.getName(), ccName.getUsername());
            }else {
                log.error("ccName为空");
            }
        }
        List<YY1_KPI> yy1KpiNameList = yy1KpiMapper.selectKPIName();
        for (ConsolidatedOrders consolidatedOrders : selectAndList) {
            // 通过ywy 对应 客户主数据表单的name拿到username。
            String targetName = consolidatedOrders.getYwy();
            String username = nameToUsernameMap.get(targetName);
            if(username!=null){
                ConsolidatedOrderVO vo  = new ConsolidatedOrderVO();
                vo.set_widget_1741241403176(consolidatedOrders.getId());
                vo.set_widget_1741241403177(consolidatedOrders.getSapid());
                vo.set_widget_1741241403180(username);

                for (YY1_KPI yy1Kpi : yy1KpiNameList){
                    if (StringUtils.isNotBlank(consolidatedOrders.getSapid()) && StringUtils.isNotBlank(yy1Kpi.getSoldToParty()) && yy1Kpi.getSoldToParty().trim().equals(consolidatedOrders.getSapid().trim())){
                        consolidatedOrders.setKhmc(yy1Kpi.getBusinessPartnerName1());
                        break;
                    }
                }

                vo.set_widget_1741241403178(consolidatedOrders.getKhmc());
                vo.set_widget_1741241403179(consolidatedOrders.getBmmcId());
                vo.set_widget_1741241403181(consolidatedOrders.getFy23_24dde());
                vo.set_widget_1741241403182(consolidatedOrders.getKhdji23());
                vo.set_widget_1741241403183(consolidatedOrders.getFy24_25dde());
                vo.set_widget_1741241403184(consolidatedOrders.getKhdji24());
                vo.set_widget_1741241403185(consolidatedOrders.getFy24_25sdyf());
                vo.set_widget_1741241403186(consolidatedOrders.getXsdd());
                vo.set_widget_1741241403187(consolidatedOrders.getCjrq());
                vo.set_widget_1741241403188(consolidatedOrders.getJdrq());
                vo.set_widget_1755582992205(consolidatedOrders.getFy25_26dde());
                vo.set_widget_1755582992206(consolidatedOrders.getKhdji25());
                vo.set_widget_1755582992207(consolidatedOrders.getFy25_26sdyf());

                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "6625db7ad51ac01aab98a910");
                parameterInster.put("entry_id", "67c948db070e1676545913c8");
                parameterInster.put("is_start_trigger", "true");
                vo.set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(vo));
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                //log.info("老客户跟踪表单新增数据--{}", jsonSale);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);

            }else {
                log.error("不存在该业务员：{}", consolidatedOrders.getYwy());
            }
        }

    }
    // 截取字符串
    public static String extractName(String aa) {
        if (StringUtils.isNotBlank(aa) && aa.contains("-")) {
            return aa.split("-")[0];
        }
        return aa;
    }


    /**
     * 统计销售订单变更时间和内容
     * @return
     */
    @XxlJob("countSalesOrderToChange")
    public String countSalesOrderToChange() {
        List<SalesOrder> salesOrderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "ne");
        List<Integer> values = new ArrayList<>();
        values.add(2);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            salesOrderList.addAll(list);
        } while (fale);
        // 新增处理逻辑：分组、排序、计算并构建ToChangeVO
        List<ToChangeVO> toChangeVOList = new ArrayList<>();

        // 1. 按销售订单号分组（_widget_1718759603973）
        Map<String, List<SalesOrder>> orderGroupMap = salesOrderList.stream()
                .filter(order -> order.get_widget_1718759603973() != null) // 过滤订单号为空的记录
                .collect(Collectors.groupingBy(SalesOrder::get_widget_1718759603973));

        // 2. 处理每个分组
        for (Map.Entry<String, List<SalesOrder>> entry : orderGroupMap.entrySet()) {
            String orderNo = entry.getKey(); // 销售订单号
            List<SalesOrder> orderList = entry.getValue();

            // 2.1 按提交时间（createTime）升序排序（最早的在前）
            orderList.sort(Comparator.comparing(SalesOrder::getCreateTime));

            // 2.2 提取第一次提交时间（作为累计天数的基准）
            if (orderList.isEmpty()) {
                continue;
            }
            SalesOrder firstOrder = orderList.getFirst();
            DateTime firstCreateTime = firstOrder.getCreateTime();
            if (firstCreateTime == null) {
                log.warn("销售订单[{}]的第一条记录提交时间为空，跳过处理", orderNo);
                continue;
            }

            // 2.3 遍历分组内的每条记录，构建ToChangeVO
            for (int i = 0; i < orderList.size(); i++) {
                SalesOrder currentOrder = orderList.get(i);
                ToChangeVO vo = new ToChangeVO();
                vo.set_id(currentOrder.get_id()); // 使用原记录的ID

                // 构建信息字符串
                String info = buildChangeInfo(i, currentOrder, firstCreateTime);
                vo.set_widget_1751512353683(info);

                toChangeVOList.add(vo);
            }
        }

        // 3. 此处可添加将toChangeVOList插入简道云表单的逻辑
        for (ToChangeVO vo : toChangeVOList) {
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "667230ad22a8581756b77d52");
            parameterInster.put("entry_id", "667230b322a8581756b78353");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", vo.get_id());
            vo.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(vo));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }

        return "处理完成，共生成" + toChangeVOList.size() + "条记录";
    }

    /**
     * 构建每条修改记录的信息字符串
     * @param index 记录索引（0表示第一次提交，1表示第二次提交，以此类推）
     * @param currentOrder 当前记录
     * @param firstCreateTime 第一次提交时间（基准时间）
     * @return 格式化的信息字符串
     */
    private String buildChangeInfo(int index, SalesOrder currentOrder, DateTime firstCreateTime) {
        // 日期格式化器（转换为"yyyy年MM月dd日"）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        // 转换第一次提交时间为LocalDate
        LocalDateTime firstCreateLdt = convertToLocalDateTime(firstCreateTime);
        if (firstCreateLdt == null) {
            return "时间格式错误：第一次提交时间无效";
        }

        // 处理当前记录的时间
        DateTime currentCreateTime = currentOrder.getCreateTime();
        LocalDateTime currentCreateLdt = convertToLocalDateTime(currentCreateTime);
        String currentCreateStr = currentCreateLdt != null ?
                currentCreateLdt.format(formatter) : "提交时间未知";

        DateTime currentReviewTime = currentOrder.getReview_date();
        LocalDateTime currentReviewLdt = convertToLocalDateTime(currentReviewTime);
        String currentReviewStr = currentReviewLdt != null ?
                currentReviewLdt.format(formatter) : "未审批";

        // 计算累计审批天数（第一次提交到当前审批的天数差）
        String daysDiffStr = "未知";
        if (currentReviewLdt != null) {
            long days = ChronoUnit.DAYS.between(firstCreateLdt.toLocalDate(), currentReviewLdt.toLocalDate());
            daysDiffStr = days + "天";
        }

        // 根据索引构建不同的信息
        if (index == 0) {
            // 第一次提交
            return String.format(
                    "第一次提交日期：%s；第一次审批通过时间：%s；累计审批天数：%s",
                    currentCreateStr, currentReviewStr, daysDiffStr
            );
        } else {
            // 第n次修改（n = index）
            String changeContent = currentOrder.get_widget_1727337368903() != null ?
                    currentOrder.get_widget_1727337368903() : "无修改内容";

            return String.format(
                    "第%d次修改内容：%s；第%d次提交日期：%s；第%d次审批通过时间：%s；累计审批天数：%s",
                    index, changeContent, index + 1, currentCreateStr, index + 1, currentReviewStr, daysDiffStr
            );
        }
    }

    /**
     * 将DateTime转换为LocalDateTime（处理空值和时区）
     */
    /**
     * 将 Joda-Time 的 DateTime 转换为 Java 8 的 LocalDateTime
     */
    private LocalDateTime convertToLocalDateTime(DateTime dateTime) {
        if (dateTime == null) {
            return null;
        }
        // 先格式化为字符串（确保格式与你的数据一致）
        String dateStr = dateTime.toString("yyyy-MM-dd HH:mm:ss");
        // 使用 Java 8 的 DateTimeFormatter 解析
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(dateStr, formatter);
    }

}
